﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using DG.Tweening;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Random = UnityEngine.Random;


/// <summary>
/// FightScene
/// </summary>
public class FightScene : MonoBehaviour
{
    /// <summary>
    /// text_current_score
    /// </summary>
    public Text text_current_score;

    /// <summary>
    /// text_highest_score
    /// </summary>
    public Text text_highest_score;

    /// <summary>
    /// 弹窗
    /// </summary>
    public Transform ui_panel_dialog;

    /// <summary>
    /// 弹窗当前分数
    /// </summary>
    public Text dialog_text_current_score;

    /// <summary>
    /// 弹窗历史最高分
    /// </summary>
    public Text dialog_text_highest_score;

    /// <summary>
    /// 看广告按钮
    /// </summary>
    public Button btn_ad_continue;

    /// <summary>
    /// 重来按钮
    /// </summary>
    public Button btn_restart;

    /// <summary>
    /// 刷新按钮
    /// </summary>
    public Button btn_refresh;

    /// <summary>
    /// 设置按钮
    /// </summary>
    public Button btn_setting;

    /// <summary>
    /// 困难
    /// </summary>
    public Button btn_hard;

    /// <summary>
    /// 中等
    /// </summary>
    public Button btn_middle;

    /// <summary>
    /// 简单
    /// </summary>
    public Button btn_easy;

    /// <summary>
    /// 
    /// </summary>
    public GameObject wait;

    /// <summary>
    /// 隐私协议按钮
    /// </summary>
    public Button btn_privacy;

    public Canvas scaler;

    /// <summary>
    /// 分享
    /// </summary>
    public Button btn_share;

    /// <summary>
    /// 关闭设置页面按钮
    /// </summary>
    public Button btn_close_setting;

    /// <summary>
    /// 服务按钮
    /// </summary>
    public Button btn_service;

    /// <summary>
    /// 选择角色
    /// </summary>
    public Button btn_select_role;

    /// <summary>
    /// 选择角色确认
    /// </summary>
    /// <returns></returns>
    public Button btn_select_finish;

    /// <summary>
    /// 选择角色按钮
    /// </summary>
    public Button btn_select_1;

    /// <summary>
    /// 选择角色按钮
    /// </summary>
    public Button btn_select_2;

    /// <summary>
    /// 选择角色按钮
    /// </summary>
    public Button btn_select_3;

    /// <summary>
    /// 选择角色按钮
    /// </summary>
    public Button btn_select_4;

    /// <summary>
    /// btn_define
    /// </summary>
    public Button btn_define;

    /// <summary>
    /// btn_close_tip
    /// </summary>
    public Button btn_close_tip;

    /// <summary>
    /// 清理
    /// </summary>
    public Button btn_clear_data;

    /// <summary>
    /// 设置面板
    /// </summary>
    public Transform ui_panel_setting;

    /// <summary>
    /// 选择难度
    /// </summary>
    public Transform ui_panel_chose_difficulty;

    /// <summary>
    /// 路
    /// </summary>
    public GameObject[] m_roadArray;

    /// <summary>
    /// 障碍物预制件(道具)
    /// </summary>
    public GameObject obstaclePrefab;

    /// <summary>
    /// ui扑克预制件
    /// </summary>
    public GameObject cardUIPrefab;

    /// <summary>
    /// 玩家手上卡牌槽
    /// </summary>
    public Transform player_card_pool;

    /// <summary>
    /// UICard的gameObject字典
    /// </summary>
    private Dictionary<string, GameObject> cardUIDic = new Dictionary<string, GameObject>();

    /// <summary>
    /// 全局路段道具字典
    /// </summary>
    private List<Dictionary<string, GameObject>> obstacleDicRoadList = new List<Dictionary<string, GameObject>>();

    /// <summary>
    /// 图集字典
    /// </summary>
    private Dictionary<string, Sprite> obstacleSpritesDic = new Dictionary<string, Sprite>();

    /// <summary>
    /// 特效预制件列表
    /// </summary>
    private List<GameObject> effectPrefabList = new List<GameObject>();

    /// <summary>
    /// 特效预制件
    /// </summary>
    public GameObject effectPrefab;

    /// <summary>
    /// EffectPoolTransform
    /// </summary>
    public Transform EffectPoolTransform;

    /// <summary>
    /// 背景影月
    /// </summary>
    public AudioSource audioBgMusic;

    /// <summary>
    /// 炸弹音效
    /// </summary>
    public AudioSource audioEffectBoom;

    /// <summary>
    /// 失败音效
    /// </summary>
    public AudioSource audioEffectFail;

    /// <summary>
    /// 人物摄像机
    /// </summary>
    /// <returns></returns>
    public Camera _3dcamera;

    /// <summary>
    /// ui相机
    /// </summary>
    public Camera _uicamera;

    /// <summary>
    /// 第一块地标志位
    /// </summary>
    private bool m_isFirst;

    /// <summary>
    /// panel_current_difficulty
    /// </summary>
    public Transform panel_current_difficulty;


    /// <summary>
    /// ui_panel_tip
    /// </summary>
    public Transform ui_panel_tip;

    /// <summary>
    ///选角界面 
    /// </summary>
    public Transform ui_panel_select_role;

    /// <summary>
    /// img_mode_easy
    /// </summary>
    public Image img_mode_easy;

    /// <summary>
    /// img_mode_mid
    /// </summary>
    public Image img_mode_mid;

    /// <summary>
    /// img_mode_hard
    /// </summary>
    public Image img_mode_hard;

    /// <summary>
    /// text_mid_highest
    /// </summary>
    public Text text_mid_highest;

    /// <summary>
    /// text_hard_highest
    /// </summary>
    public Text text_hard_highest;

    /// <summary>
    /// text_easy_highest
    /// </summary>
    public Text text_easy_highest;

    /// <summary>
    /// img_bg_easy
    /// </summary>
    public Image img_bg_easy;

    /// <summary>
    /// img_bg_mid
    /// </summary>
    public Image img_bg_mid;

    /// <summary>
    /// img_bg_hard
    /// </summary>
    public Image img_bg_hard;

    /// <summary>
    /// f_10可选角色
    /// </summary>
    public Transform f_10;

    /// <summary>
    /// f_5可选角色
    /// </summary>
    public Transform f_5;

    /// <summary>
    /// f_11可选角色
    /// </summary>
    public Transform f_11;

    /// <summary>
    /// f_22可选角色
    /// </summary>
    public Transform f_22;
    
    /// <summary>
    /// AndroidJavaObject
    /// </summary>
    private AndroidJavaObject _androidJavaObject;
    
    
    
    /// <summary>
    /// start
    /// </summary>
    void Start()
    {
        Init();
    }

    /// <summary>
    /// 初始化
    /// </summary>
    private void Init()
    {
        InitResources();
        InitData();
        InitGameObjectDic();
        InitUI();
        InitButtonClick();
        ExchangeRole();
        m_isFirst = true;
    }

    /// <summary>
    /// 初始化角色
    /// </summary>
    private void ExchangeRole()
    {
        f_10.gameObject.SetActive(BattleLogic.getInstance().GetCurrentRoleName().Equals("f_10"));
        f_5.gameObject.SetActive(BattleLogic.getInstance().GetCurrentRoleName().Equals("f_5"));
        f_11.gameObject.SetActive(BattleLogic.getInstance().GetCurrentRoleName().Equals("f_11"));
        f_22.gameObject.SetActive(BattleLogic.getInstance().GetCurrentRoleName().Equals("f_22"));
    }


    /// <summary>
    /// InitButtonClick
    /// </summary>
    private void InitButtonClick()
    {
        //按钮注册事件
        btn_refresh.onClick.RemoveAllListeners();
        btn_refresh.onClick.AddListener(btn_refresh_clicked);
        //设置按钮
        btn_setting.onClick.RemoveAllListeners();
        btn_setting.onClick.AddListener(btn_setting_onClick);
        ///设置页面关闭
        btn_close_setting.onClick.RemoveAllListeners();
        btn_close_setting.onClick.AddListener(btn_close_setting_onClick);
        //隐私协议
        btn_privacy.onClick.RemoveAllListeners();
        btn_privacy.onClick.AddListener(btn_privacy_onClick);
        //服务协议
        btn_service.onClick.RemoveAllListeners();
        btn_service.onClick.AddListener(btn_service_onClick);
        //分享
        btn_share.onClick.RemoveAllListeners();
        btn_share.onClick.AddListener(btn_share_onClick);
        ///困难选择
        btn_hard.onClick.RemoveAllListeners();
        btn_hard.onClick.AddListener(btn_hard_onclick);
        ///中等选择
        btn_middle.onClick.RemoveAllListeners();
        btn_middle.onClick.AddListener(btn_middle_onClick);
        ///简单选择
        btn_easy.onClick.RemoveAllListeners();
        btn_easy.onClick.AddListener(btn_easy_onClick);
        //选择角色面板
        btn_select_role.onClick.RemoveAllListeners();
        btn_select_role.onClick.AddListener(btn_select_role_click);
        //选择角色确认
        btn_select_finish.onClick.RemoveAllListeners();
        btn_select_finish.onClick.AddListener(btn_select_finish_click);

        btn_select_1.onClick.RemoveAllListeners();
        btn_select_1.onClick.AddListener(() => { btn_select_index_click(1); });

        btn_select_2.onClick.RemoveAllListeners();
        btn_select_2.onClick.AddListener(() => { btn_select_index_click(2); });

        btn_select_3.onClick.RemoveAllListeners();
        btn_select_3.onClick.AddListener(() => { btn_select_index_click(3); });

        btn_select_4.onClick.RemoveAllListeners();
        btn_select_4.onClick.AddListener(() => { btn_select_index_click(4); });

        btn_define.onClick.RemoveAllListeners();
        btn_define.onClick.AddListener(btn_define_click);

        btn_close_tip.onClick.RemoveAllListeners();
        btn_close_tip.onClick.AddListener(btn_close_tip_click);

        btn_clear_data.onClick.RemoveAllListeners();
        btn_clear_data.onClick.AddListener(btn_clear_data_click);
    }

    /// <summary>
    /// btn_clear_data_click
    /// </summary>
    private void btn_clear_data_click()
    {
        ui_panel_tip.gameObject.SetActive(true);
    }

    /// <summary>
    /// btn_close_tip_click
    /// </summary>
    private void btn_close_tip_click()
    {
        ui_panel_tip.gameObject.SetActive(false);
    }

    /// <summary>
    /// btn_define (清理操作)
    /// </summary>
    private void btn_define_click()
    {
        foreach (string modeName in GameConfig.modeKey)
        {
            if (PlayerPrefs.HasKey(modeName))
            {
                PlayerPrefs.DeleteKey(modeName);
            }
        }   
        
        Debug.Log("清理缓存完毕");
#if !UNITY_EDITOR
        _androidJavaObject.Call("loginout");
#else
        LoginOut();
#endif
    }
    
    /// <summary>
    /// LoginOut
    /// </summary>
    public void LoginOut()
    {
        SceneManager.LoadScene("F0");
    }
    
    /// <summary>
    /// btn_select_index_click
    /// </summary>
    /// <param name="index"></param>
    private void btn_select_index_click(int index)
    {
        BattleLogic.getInstance().SetCurentRoleName(GameConfig.ConfigRoleName[index - 1]);
        UpdateCurrentSelectRole();
    }

    /// <summary>
    /// 当前选择的角色
    /// </summary>
    private void UpdateCurrentSelectRole()
    {
        string currentSelectRoleName = BattleLogic.getInstance().GetCurrentRoleName();
        int curIndex = 1;
        for (int index = 0; index < GameConfig.ConfigRoleName.Length; index++)
        {
            if (GameConfig.ConfigRoleName[index].Equals(currentSelectRoleName))
            {
                curIndex = index + 1;
                break;
            }
        }

        btn_select_1.transform.Find("img_selected").gameObject.SetActive(curIndex == 1);
        btn_select_2.transform.Find("img_selected").gameObject.SetActive(curIndex == 2);
        btn_select_3.transform.Find("img_selected").gameObject.SetActive(curIndex == 3);
        btn_select_4.transform.Find("img_selected").gameObject.SetActive(curIndex == 4);
    }


    /// <summary>
    /// 选择角色完毕
    /// </summary>
    private void btn_select_finish_click()
    {
        ExchangeRole();
        BattleLogic.getInstance().SetIsPause(false);
        ui_panel_select_role.gameObject.SetActive(false);
    }

    /// <summary>
    /// btn_select_role_click
    /// </summary>
    private void btn_select_role_click()
    {
        ///暂停游戏
        BattleLogic.getInstance().SetIsPause(true);
        ///显示面板
        ui_panel_select_role.gameObject.SetActive(true);
        UpdateCurrentSelectRole();
    }


    private void Awake()
    {
        SetOrientationPortrait();
#if !UNITY_EDITOR
        _androidJavaObject = new AndroidJavaObject("com.poker.runwin.LoginUtils");
#endif
    }

    /// <summary>
    /// 加载图集资源
    /// </summary>
    private void InitResources()
    {
        if (obstacleSpritesDic == null)
        {
            obstacleSpritesDic = new Dictionary<string, Sprite>();
        }
        else
        {
            obstacleSpritesDic.Clear();
        }

        ///图集资源加载
        Sprite[] sprites = Resources.LoadAll<Sprite>("UI/Cards/cards");
        for (int index = 0; index < sprites.Length; index++)
        {
            obstacleSpritesDic.Add(sprites[index].name, sprites[index]);
        }
    }

    /// <summary>
    /// 初始化数据
    /// </summary>
    private void InitData()
    {
        //初始化卡池
        BattleCardPoolLogic.getInstance().InitPool();
        //初始化数据
        BattleLogic.getInstance().InitData();
    }

    /// <summary>
    /// 清理路段字典
    /// </summary>
    private void ClearObstacleDic()
    {
        for (int index = 0; index < obstacleDicRoadList.Count; index++)
        {
            if (obstacleDicRoadList[index] != null)
            {
                ClearGameObjectDic(obstacleDicRoadList[index]);
            }
        }
    }


    /// <summary>
    /// 初始化gameobject字典
    /// </summary>
    private void InitGameObjectDic()
    {
        if (effectPrefabList == null)
        {
            effectPrefabList = new List<GameObject>();
        }
        else
        {
            ClearEffectPrefabList();
        }

        if (cardUIDic == null)
        {
            cardUIDic = new Dictionary<string, GameObject>();
        }
        else
        {
            cardUIDic.Clear();
        }

        ///初始化字典
        if (obstacleDicRoadList.Count > 0)
        {
            ClearObstacleDic();
        }
        else
        {
            obstacleDicRoadList = new List<Dictionary<string, GameObject>>();
            for (int index = 0; index < 5; index++)
            {
                Dictionary<String, GameObject> roadDic = new Dictionary<string, GameObject>();
                obstacleDicRoadList.Add(roadDic);
            }
        }


        //创建初始化地形
        for (int index = 1; index < m_roadArray.Length; index++)
        {
            RandomGenerateObstacleInOnRoad(index);
        }
    }

    /// <summary>
    /// 清理道具字典(路段更新)
    /// </summary>
    /// <param name="dic"></param>
    private void obstacleDicClearDic(Dictionary<string, GameObject> dic)
    {
        if (dic.Count == 0)
        {
            return;
        }

        foreach (var item in dic)
        {
            if (item.Value != null)
            {
                Destroy(item.Value);
                string[] spriteNameArray = item.Key.Split('_');
                string kindName = spriteNameArray[3] + "_" + spriteNameArray[4];
                if (kindName != "tb_qipai" && kindName != "tb_zhadan" && kindName != "tb_mopai")
                {
                    BattleCardPoolLogic.getInstance().AddCardInBattlePoolBySpriteName(kindName);
                }
            }
        }

        dic.Clear();
    }


    /// <summary>
    /// 在一条路上随机产生道具
    /// </summary>
    private void RandomGenerateObstacleInOnRoad(int index)
    {
        int random_num = Random.Range(1, 3);
        if (random_num == 1)
        {
            //显示1个
            int random_pos = Random.Range(1, 4);
            Transform random_pos_transform =
                GameObject.Find("roadParagraph" + index + "/obstaclePos" + random_pos).transform;
            GameObject prefab = Instantiate(obstaclePrefab, random_pos_transform);
            prefab.transform.localPosition = new Vector3(0, 1f, 0);
            ObstacleDataModel _obstacleDataModel = BattleLogic.getInstance().GetRandomObstacle();
            prefab.GetComponent<SpriteRenderer>().sprite =
                obstacleSpritesDic[_obstacleDataModel.GetCardSpriteName()];
            string obstacleName = "ob_" + index + "_" + random_pos + "_" + _obstacleDataModel.GetCardSpriteName();
            obstacleDicRoadList[index].Add(obstacleName, prefab);
            prefab.name = obstacleName;
        }
        else
        {
            //显示3个
            for (int target = 1; target < 4; target++)
            {
                Transform random_pos_transform =
                    GameObject.Find("roadParagraph" + index + "/obstaclePos" + target).transform;
                GameObject prefab = Instantiate(obstaclePrefab, random_pos_transform);
                prefab.transform.localPosition = new Vector3(0, 1f, 0);
                ObstacleDataModel _obstacleDataModel = BattleLogic.getInstance().GetRandomObstacle();
                prefab.GetComponent<SpriteRenderer>().sprite =
                    obstacleSpritesDic[_obstacleDataModel.GetCardSpriteName()];
                string obstacleName = "ob_" + index + "_" + target + "_" + _obstacleDataModel.GetCardSpriteName();
                obstacleDicRoadList[index].Add(obstacleName, prefab);
                prefab.name = obstacleName;
            }
        }
    }

    /// <summary>
    /// 初始化UI数据
    /// </summary>
    private void InitUI()
    {
        PlayerPrefsData playerData = BattleLogic.getInstance().GetLocalPlayerData();
        //获取历史最高分
        text_highest_score.text = playerData.getHighestScore().ToString();
        //设置当前分数
        text_current_score.text = BattleLogic.getInstance().GetCurrentScore().ToString();
        //死亡面板隐藏
        ui_panel_dialog.gameObject.SetActive(false);
        //设置面板隐藏
        ui_panel_setting.gameObject.SetActive(false);
        //隐藏
        ui_panel_select_role.gameObject.SetActive(false);
        //提示关闭
        ui_panel_tip.gameObject.SetActive(false);
        //暂停游戏
        BattleLogic.getInstance().SetIsPause(true);
        //显示选择难度面板
        ui_panel_chose_difficulty.gameObject.SetActive(true);
        ///
        text_easy_highest.text = PlayerPrefs.GetInt(GameConfig.modeKey[0]) + "";
        text_mid_highest.text = PlayerPrefs.GetInt(GameConfig.modeKey[1]) + "";
        text_hard_highest.text = PlayerPrefs.GetInt(GameConfig.modeKey[2]) + "";
        panel_current_difficulty.gameObject.SetActive(false);
    }


    /// <summary>
    /// btn_hard_onclick(困难选择)
    /// </summary>
    public void btn_hard_onclick()
    {
        ChoseDiffcultyAndStartGame(2);
    }

    /// <summary>
    /// btn_middle_onClick(普通选择)
    /// </summary>
    public void btn_middle_onClick()
    {
        ChoseDiffcultyAndStartGame(1);
    }

    /// <summary>
    /// btn_easy_onClick(简单选择)
    /// </summary>
    public void btn_easy_onClick()
    {
        ChoseDiffcultyAndStartGame(0);
    }

    /// <summary>
    /// ChoseDiffcultyAndStartGame
    /// </summary>
    private void ChoseDiffcultyAndStartGame(int diffculty)
    {
        BattleLogic.getInstance().setDiffculty(diffculty);
        ui_panel_chose_difficulty.gameObject.SetActive(false);
        BattleLogic.getInstance().SetIsPause(false);
        audioBgMusic.Play();
    }


    /// <summary>
    /// 分享
    /// </summary>
    public void btn_share_onClick()
    {
        Debug.Log("分享");
        transform.GetComponent<AndroidMgr>()
            .OnShareToAndroid("https://play.google.com/store/apps/details?id=com.poker.runwin");
    }

    /// <summary>
    /// 弹窗
    /// </summary>
    private void ShowDialog()
    {
        if (ui_panel_dialog.gameObject.activeSelf)
            return;

        audioBgMusic.Stop();
        audioEffectFail.Play();
        ui_panel_dialog.gameObject.SetActive(true);
        //当前分数
        dialog_text_current_score.text = BattleLogic.getInstance().GetCurrentScore().ToString();
        //历史最高分
        PlayerPrefsData playerData = BattleLogic.getInstance().GetLocalPlayerData();
        dialog_text_highest_score.text = playerData.getHighestScore().ToString();

        btn_ad_continue.onClick.RemoveAllListeners();
        btn_ad_continue.onClick.AddListener(btn_ad_continue_clicked);

        btn_restart.onClick.RemoveAllListeners();
        btn_restart.onClick.AddListener(btn_restart_clicked);
    }

    /// <summary>
    /// 隐私协议
    /// </summary>
    private void btn_privacy_onClick()
    {
        Application.OpenURL("https://www.kessnen2568.online/protocol/Privacy_policy.html");
    }

    /// <summary>
    /// 服务协议
    /// </summary>
    private void btn_service_onClick()
    {
        Application.OpenURL("https://www.kessnen2568.online/protocol/Terms_of_service.html");
    }

    /// <summary>
    /// 设置按钮点击
    /// </summary>
    private void btn_setting_onClick()
    {
        if (ui_panel_setting.gameObject.activeSelf)
            return;
        ui_panel_setting.gameObject.SetActive(true);
        audioBgMusic.Stop();
        BattleLogic.getInstance().SetIsPause(true);
    }

    /// <summary>
    /// 设置页面关闭
    /// </summary>
    private void btn_close_setting_onClick()
    {
        if (!ui_panel_setting.gameObject.activeSelf)
            return;
        ui_panel_setting.gameObject.SetActive(false);
        audioBgMusic.Play();
        BattleLogic.getInstance().SetIsPause(false);
    }

    /// <summary>
    /// 关闭弹窗
    /// </summary>
    private void CloseDialog()
    {
        if (!ui_panel_dialog.gameObject.activeSelf)
            return;

        ui_panel_dialog.gameObject.SetActive(false);
    }


    /// <summary>
    /// 碰撞到障碍物(出发动画和计算分数)
    /// </summary>
    public void collisionObstacle(string obstacleName)
    {
        string[] obstacleNameArray = obstacleName.Split('_');
        //第几个路段
        int index = int.Parse(obstacleNameArray[1]);
        string kindName = obstacleNameArray[3] + "_" + obstacleNameArray[4];


        if (kindName == "tb_qipai")
        {
            //清理缓存
            if (obstacleDicRoadList[index].ContainsKey(obstacleName))
            {
                Destroy(obstacleDicRoadList[index][obstacleName]);
            }


            if (cardUIDic.Count > 0)
            {
                ///需要弃额牌是
                string needQiCard = BattleLogic.getInstance().RandomRemoveCardInPool();
                if (cardUIDic.ContainsKey(needQiCard))
                {
                    Destroy(cardUIDic[needQiCard]);
                    cardUIDic.Remove(needQiCard);
                }

                //从玩家牌池移除这张牌
                BattleLogic.getInstance().RemoveCardFromPlayerCardPool(needQiCard);
                //弃牌回收进战场池子
                BattleCardPoolLogic.getInstance().AddCardInBattlePoolBySpriteName(needQiCard);
            }
        }
        else if (kindName == "tb_zhadan")
        {
            Action action = () =>
            {
                //清理缓存
                if (obstacleDicRoadList[index].ContainsKey(obstacleName))
                {
                    //将撞到的道具销毁
                    Destroy(obstacleDicRoadList[index][obstacleName]);
                }
            };

            obstacleDicRoadList[index][obstacleName].GetComponent<SpineObstacle>().ShowBoom(action);
            audioEffectBoom.Play();
            //吃到炸弹抖屏特效
            _3dcamera.DOShakePosition(0.2f, 2, 10, 50, true);
            int current_blood = BattleLogic.getInstance().GetCurrentBlood();
            BattleLogic.getInstance().SetCurrentBlood(current_blood - 1);
        }
        else if (kindName == "tb_mopai")
        {
            if (cardUIDic.Count >= 13)
            {
                print("牌数量已达上限");
                return;
            }

            //清理缓存
            if (obstacleDicRoadList[index].ContainsKey(obstacleName))
            {
                Action actionGetCard = () =>
                {
                    ObstacleDataModel _obstacleDataModel = BattleCardPoolLogic.getInstance().randomGetCardInPool();
                    string randomCardName = _obstacleDataModel.GetCardSpriteName();
                    ///玩家的池子里加入这张牌
                    BattleLogic.getInstance().AddPlayerCardPool(randomCardName);
                    //从战场池子里移除这张牌
                    // BattleCardPoolLogic.getInstance().RemoveCardInBattlePoolBySpriteName(randomCardName);
                    //预制件初始化
                    GameObject prefab = Instantiate(cardUIPrefab, player_card_pool);
                    prefab.GetComponent<Image>().sprite = obstacleSpritesDic[randomCardName];
                    cardUIDic.Add(randomCardName, prefab);
                    prefab.GetComponent<SpineCard>().ShowMoPai();
                    ///检测是否有顺子
                    List<string> needDeleteCardList = BattleLogic.getInstance().CheckPlayerCardPool();
                    NeedDeletePlayerCardPrefab(needDeleteCardList);
                };

                // Vector3 screenPosition = _uicamera.WorldToScreenPoint(obstacleDicRoadList[index][obstacleName].transform.position);
                actionGetCard();
                //飞特效
                // MoveEffect(screenPosition,player_card_pool,0.5f,actionGetCard);
                //将撞到的道具销毁
                Destroy(obstacleDicRoadList[index][obstacleName]);
            }
        }
        else
        {
            if (cardUIDic.Count >= 13)
            {
                print("牌数量已达上限");
                BattleCardPoolLogic.getInstance().AddCardInBattlePoolBySpriteName(kindName);
                return;
            }

            //清理缓存
            if (obstacleDicRoadList[index].ContainsKey(obstacleName))
            {
                //将撞到的道具销毁
                Action actionGetCard = () =>
                {
                    ///玩家的池子里加入这张牌
                    BattleLogic.getInstance().AddPlayerCardPool(kindName);
                    //预制件初始化
                    GameObject prefab = Instantiate(cardUIPrefab, player_card_pool);
                    prefab.GetComponent<Image>().sprite = obstacleSpritesDic[kindName];
                    cardUIDic.Add(kindName, prefab);
                    prefab.GetComponent<SpineCard>().ShowMoPai();
                    ///检测是否有顺子
                    List<string> needDeleteCardList = BattleLogic.getInstance().CheckPlayerCardPool();
                    NeedDeletePlayerCardPrefab(needDeleteCardList);
                };

                // Vector3 screenPosition = _uicamera.WorldToScreenPoint(obstacleDicRoadList[index][obstacleName].transform.position);

                actionGetCard();
                //飞特效
                // MoveEffect(screenPosition,player_card_pool,0.5f,actionGetCard);
                Destroy(obstacleDicRoadList[index][obstacleName]);
            }
        }
    }

    /// <summary>
    /// 需要移除玩家槽中卡牌的预制件
    /// </summary>
    /// <param name="needDeleteCardSpriteNameList"></param>
    private void NeedDeletePlayerCardPrefab(List<string> needDeleteCardSpriteNameList)
    {
        if (needDeleteCardSpriteNameList.Count <= 0)
            return;

        for (int index = 0; index < needDeleteCardSpriteNameList.Count; index++)
        {
            string key = needDeleteCardSpriteNameList[index];
            if (cardUIDic[key] != null)
            {
                Action SpineCardAction = () =>
                {
                    Action EffectMoveAction = () =>
                    {
                        Destroy(cardUIDic[key]);
                        cardUIDic.Remove(key);
                    };
                    MoveEffect(cardUIDic[key].transform, text_current_score.transform, 0.5f, EffectMoveAction);
                };

                cardUIDic[key].GetComponent<SpineCard>().ShowShunZiAnimation(SpineCardAction);
                int currentScore = BattleLogic.getInstance().GetCurrentScore();
                int nextScore = currentScore + needDeleteCardSpriteNameList.Count;
                BattleLogic.getInstance().SetCurrentScore(nextScore);
                ///从玩家逻辑池中移除牌
                BattleLogic.getInstance().RemoveCardFromPlayerCardPool(key);
                ///顺子移除的牌加到战场池中
                BattleCardPoolLogic.getInstance().AddCardInBattlePoolBySpriteName(key);
            }
        }
    }

    /// <summary>
    /// 刷新按钮
    /// </summary>
    private void btn_refresh_clicked()
    {
        SceneManager.LoadScene("Fight");
    }


    /// <summary>
    /// 按钮点击（继续按钮）
    /// </summary>
    public void btn_ad_continue_clicked()
    {
        // Debug.Log("btn_ad_continue_clicked");

        StartCoroutine(LoadWaid());

        //wait.transform.GetChild(0).DOLocalRotate(new Vector3(0, 0, 360 * 5), 2).SetEase(Ease.Linear).OnComplete(()=> {
        //    wait.gameObject.SetActive(false);
        //});
    }

    IEnumerator LoadWaid()
    {
        wait.gameObject.SetActive(true);
        yield return new WaitForSeconds(2);
        wait.gameObject.SetActive(false);
    }


    public void ContinueFunc()
    {
        CloseDialog();
        BattleLogic.getInstance().SetCurrentBlood(1);
        BattleLogic.getInstance().SetIsPause(false);
        audioBgMusic.Play();
    }

    /// <summary>
    /// 重来按钮点击
    /// </summary>
    private void btn_restart_clicked()
    {
        SceneManager.LoadScene("Fight");
    }

    /// <summary>
    /// 切换为竖屏
    /// </summary>
    public void SetOrientationPortrait()
    {
        //设置竖屏
        Screen.orientation = ScreenOrientation.Portrait;
    }

    /// <summary>
    /// onGui事件
    /// </summary>
    private void OnGUI()
    {
        //游戏暂停或者已经输的情况下
        if (BattleLogic.getInstance().GetIsLose() || BattleLogic.getInstance().GetIsPause())
        {
            return;
        }

        //弹窗提示
        if (BattleLogic.getInstance().GetCurrentBlood() == 0)
        {
            BattleLogic.getInstance().SetIsPause(true);
            ShowDialog();
            return;
        }

        //设置当前分数
        if (text_current_score != null)
        {
            text_current_score.text = BattleLogic.getInstance().GetCurrentScore().ToString();
        }

        if (text_highest_score != null)
        {
            text_highest_score.text = BattleLogic.getInstance().GetLocalPlayerData().getHighestScore().ToString();
        }

        if (panel_current_difficulty != null)
        {
            panel_current_difficulty.gameObject.SetActive(true);
            img_mode_easy?.gameObject.SetActive(BattleLogic.getInstance().getDiffculty() == 0);
            img_mode_mid?.gameObject.SetActive(BattleLogic.getInstance().getDiffculty() == 1);
            img_mode_hard?.gameObject.SetActive(BattleLogic.getInstance().getDiffculty() == 2);
        }


        img_bg_easy?.gameObject.SetActive(BattleLogic.getInstance().getDiffculty() == 0);
        img_bg_mid?.gameObject.SetActive(BattleLogic.getInstance().getDiffculty() == 1);
        img_bg_hard?.gameObject.SetActive(BattleLogic.getInstance().getDiffculty() == 2);
    }

    /// <summary>
    /// 动态移动路的预制件
    /// </summary>
    /// <param name="index"></param>
    public void generate_road(int index)
    {
        if (index == 0 && m_isFirst)
        {
            m_isFirst = false;
            return;
        }
        else
        {
            int lastIndex = index - 1;
            if (lastIndex < 0)
                lastIndex = 4;
            //当前到达的路段的上一条路段进行切换，也就是说达到第二条路段，将第一条路段进行切换
            m_roadArray[lastIndex].transform.position =
                m_roadArray[lastIndex].transform.position + new Vector3(150, 0, 0);
            //随机生成道具 如果生成卡牌的话只能从池里取
            random_produce_props(lastIndex);
        }
    }

    /// <summary>
    /// 随机产生道具
    /// </summary>
    private void random_produce_props(int index)
    {
        //清空原有道具
        if (obstacleDicRoadList[index].Count > 0)
        {
            obstacleDicClearDic(obstacleDicRoadList[index]);
        }

        //产生道具
        RandomGenerateObstacleInOnRoad(index);
    }

    /// <summary>
    /// 销毁
    /// </summary>
    private void OnDestroy()
    {
        ClearScene();
    }

    /// <summary>
    /// 清理gameObjectArray
    /// </summary>
    private void ClearGameObjectArray(ref GameObject[] gameObjectsArray)
    {
        for (int index = 0; index < gameObjectsArray.Length; index++)
        {
            if (gameObjectsArray[index] != null)
            {
                Destroy(gameObjectsArray[index]);
            }
        }
    }

    /// <summary>
    /// 清理字典
    /// </summary>
    /// <param name="dic"></param>
    private void ClearGameObjectDic<T>(Dictionary<T, GameObject> dic)
    {
        foreach (var item in dic)
        {
            if (item.Value != null)
            {
                Destroy(item.Value);
            }
        }

        dic.Clear();
    }

    /// <summary>
    /// 清理特效预制件列表
    /// </summary>
    private void ClearEffectPrefabList()
    {
        if (effectPrefabList.Count == 0)
        {
            return;
        }

        for (int index = 0; index < effectPrefabList.Count; index++)
        {
            if (effectPrefabList[index] != null)
            {
                Destroy(effectPrefabList[index]);
            }
        }

        effectPrefabList.Clear();
    }

    /// <summary>
    /// 移动
    /// </summary>
    /// <param name="action"></param>
    private void MoveEffect(Transform transformStart, Transform endTransform, float time = 1, Action action = null)
    {
        GameObject _effectPrefab = Instantiate(effectPrefab, EffectPoolTransform);
        //开始坐标
        _effectPrefab.transform.position = transformStart.position;
        effectPrefabList.Add(_effectPrefab);
        _effectPrefab.transform.DOMove(endTransform.position, time)
            .SetAutoKill(false)
            .OnComplete(() =>
            {
                if (action != null)
                {
                    action();
                }

                Destroy(_effectPrefab);
            });
    }


    /// <summary>
    /// 清理场景
    /// </summary>
    private void ClearScene()
    {
        btn_ad_continue.onClick.RemoveAllListeners();
        btn_restart.onClick.RemoveAllListeners();
        btn_refresh.onClick.RemoveAllListeners();
        btn_close_setting.onClick.RemoveAllListeners();
        btn_privacy.onClick.RemoveAllListeners();
        btn_service.onClick.RemoveAllListeners();
        btn_setting.onClick.RemoveAllListeners();
        btn_share.onClick.RemoveAllListeners();
        btn_hard.onClick.RemoveAllListeners();
        btn_middle.onClick.RemoveAllListeners();
        btn_easy.onClick.RemoveAllListeners();
        btn_select_role.onClick.RemoveAllListeners();
        btn_select_finish.onClick.RemoveAllListeners();
        btn_select_1.onClick.RemoveAllListeners();
        btn_select_2.onClick.RemoveAllListeners();
        btn_select_3.onClick.RemoveAllListeners();
        btn_select_4.onClick.RemoveAllListeners();
        btn_define.onClick.RemoveAllListeners();
        btn_close_tip.onClick.RemoveAllListeners();
        btn_clear_data.onClick.RemoveAllListeners();
        ClearGameObjectArray(ref m_roadArray);
        ClearGameObjectDic<string>(cardUIDic);
        ClearEffectPrefabList();
        obstacleSpritesDic.Clear();
        Resources.UnloadUnusedAssets();
        ClearObstacleDic();
        Destroy(audioBgMusic);
        Destroy(audioEffectBoom);
        Destroy(audioEffectFail);
        print("资源回收完毕");
    }
}